import Taro, { Component, Config, getCurrentPages } from '@tarojs/taro'
import { Image, View, Text, ScrollView, Button } from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui';
import { observer, inject } from '@tarojs/mobx'
import '@tarojs/async-await'
import Stores from '../../../stores/storeIdentifier'
import './index.scss'
import OrderStore from '../../../stores/orderStore'
import { OrderDto } from '../../../services/order/dto/orderDto'
import { PagedList } from '../../../services/dto/pagedList'
import { OrderQueryStatus } from '../../../services/order/dto/OrderQueryStatus'
import { OrderStatus } from '../../../services/order/dto/OrderStatus'
import { JsApiReturnModel } from '../../../services/dto/jsApiReturnModel';
import WxOpenStore from '../../../stores/wxOpenStore';

export interface IIndexProps {
  orderStore: OrderStore,
  wxOpenStore: WxOpenStore
}

@inject(Stores.OrderStore,Stores.WxOpenStore)
@observer
class Index extends Component<IIndexProps> {
  jsApiModel: JsApiReturnModel
  constructor(props) {
    super(props)

    if (this.$router.params.status) {
      let current = this.list.findIndex(m => m.value === parseInt(this.$router.params.status))
      this.setState({ status: this.$router.params.status, current: current })
    }
  }
  orderFlag = false
  list: Array<any> = [{ title: '全部', value: '' },
  { title: '待付款', value: OrderQueryStatus.WaitPay },
  { title: '待发货', value: OrderQueryStatus.PaidAndWaitShip },
  { title: '待收货', value: OrderQueryStatus.ShippedAndWaitReceipt },
  { title: '已完成', value: OrderQueryStatus.Completed }]
  orders?: PagedList<OrderDto>
  config: Config = {
    navigationBarTitleText: '我的订单'
  }
  state = {
    current: 0,
    needload: true,
    value: '',
    skipCount: 0,
    maxResultCount: 10,
    sorting: 'id desc',
    status: ''
  }

  async componentWillMount() {
    await this.getMyOrderPaged()
  }

  async componentDidShow() {
    let pages = getCurrentPages()
    if (pages) {
      let prev = pages[pages.length - 1]
      if (prev.data.orderFlag) {
        prev.setData({
          orderFlag: false
        })
        this.handleAndGetMyOrderPaged(prev.data.current)
      }
    }
  }

  async getMyOrderPaged() {
    await this.props.orderStore.getMyOrderPagedList({
      maxResultCount: this.state.maxResultCount,
      skipCount: this.state.skipCount,
      sorting: this.state.sorting,
      status: this.state.status
    })
    let orders = this.props.orderStore.orders
    let needload

    if (this.orders) {
      this.orders.currentPage = orders.currentPage;
      this.orders.skipCount = orders.skipCount;
      this.orders.totalCount = orders.totalCount;
      this.orders.totalPages = orders.totalPages;
      this.orders.maxResultCount = orders.maxResultCount;
      this.orders.items = [...this.orders.items, ...orders.items]
      if (this.orders.items.length >= orders.totalCount)
        needload = false
      else {
        needload = true
      }
    } else {
      this.orders = orders
      needload = true
    }
    this.setState({ needload: needload })

  }

  handleClick(value) {
    if (this.state.current === value) {
      return
    }
    this.handleAndGetMyOrderPaged(value)
  }

  handleAndGetMyOrderPaged(value) {
    console.log(this.list[value].value);
    if (this.orders) {
      this.orders = undefined
    }
    this.setState({
      current: value,
      skipCount: 0,
      status: this.list[value].value,
      needload: true
    }, async () => {
      await this.getMyOrderPaged();
    })
  }

  onScrollToLower = async () => {
    this.setState({ skipCount: this.state.skipCount + this.state.maxResultCount }, async () => {
      if (this.state.needload)
        await this.getMyOrderPaged();
    })
  }
  onGetPay = async (id, e) => {

    e.stopPropagation()
    await this.props.orderStore.getApiPay(id)
    this.jsApiModel = this.props.orderStore.jsApiModel

    if (this.jsApiModel) {
      var _package = this.jsApiModel.package as string
      var _prepay_id = _package.replace('prepay_id=', '')
      await this.props.wxOpenStore.createFormIds([{ formId: _prepay_id, formIdType: 1 }])
      let this_ = this
      Taro.requestPayment({
        timeStamp: this.jsApiModel.timestamp,
        nonceStr: this.jsApiModel.nonceStr,
        package: this.jsApiModel.package,
        signType: this.jsApiModel.signType,
        paySign: this.jsApiModel.paySign,
        async success(res) {
          this_.gotoOrderResult(id)
          this_.setState({})
        },
      }).then((res) => {

      })
    }
  }

  onCancelOrder = async (id, e) => {
    e.stopPropagation()
    await this.props.orderStore.cancelOrder(id)
    await this.handleAndGetMyOrderPaged(this.state.current)
  }

  gotoOrderDetail = (id, e) => {
    Taro.navigateTo({
      url: '/pages/profile/order/detail?id=' + id
    })
  }

  gotoExpress(code, number, e) {
    e.stopPropagation();
    Taro.navigateTo({
      url: '/pages/profile/order/logistics?code=' + code + '&express=' + number
    })
  }

  gotoComment(id, e) {
    e.stopPropagation()
    Taro.navigateTo({ url: '/pages/profile/order/comment-list?id=' + id })
  }

  gotoOrderResult(id) {
    this.setState({})
    Taro.navigateTo({
      url: '/pages/order/result?id=' + id + '&type=' + 1
    })
  }
  async confirmResolve(id, e) {
    e.stopPropagation()
    await this.props.orderStore.confirmReceive(id)
    await this.handleAndGetMyOrderPaged(this.state.current)
  }

  render() {
    return (
      <View className='order-wrap'>
        <AtTabs
          className='order-tab'
          current={this.state.current}
          scroll
          tabList={this.list}
          onClick={this.handleClick.bind(this)}
        >
          {
            this.list.map((t, index) => (
              <AtTabsPane current={this.state.current} index={index}>
                <ScrollView
                  className='scrollview'
                  scrollY
                  scrollWithAnimation
                  style='height: 100%'
                  onScrollToLower={this.onScrollToLower}
                >
                  {
                    this.orders && this.orders.items.map((item) => (
                      <View className='order-panel ratina-bd bd-t bd-b' onClick={this.gotoOrderDetail.bind(this, item.id)}>
                        <View className='order-panel-header ratina-bd bd-b'>
                          <Text>订单编号:{item.id}</Text>
                          {/* taro-ui 冒泡不支持 <AtIcon value='trash' size='16' color='#333' onClick={this.deleteOrder.bind(this,item.id)}/> */}
                        </View>
                        <View className='order-panel-body'>
                          <View className='order-info'>
                            <View className='media'>
                              {
                                item.orderItems.map((product) => (
                                  <Image mode='aspectFill' src={product.featuredImage} />
                                ))
                              }
                              {item.orderItems.length == 1 && (
                                <View className='media-bd'>
                                  <View className='h4'>{item.orderItems[0].productName}</View>
                                  {item.orderItems[0].skuName && <View className='p'>{item.orderItems[0].skuName}</View>}
                                </View>
                              )}

                            </View>
                            <View className='tips'>
                              {item.status.toString() != OrderStatus.Completed.toString() && <Text className='danger'>{item.statusDisplayName}</Text>}
                              {item.status.toString() == OrderStatus.Completed.toString() && <Text className='success'>{item.statusDisplayName}</Text>}
                              <Text>包裹1</Text>
                              <Text className='price'>￥{item.finalPrice}</Text>
                            </View>
                          </View>
                        </View>
                        {
                          item.status.toString() === OrderStatus.WaitPay.toString() && (
                            <View className='order-panel-footer ratina-bd bd-t'>
                              {item.receiptUserName && <Button type='primary' size='mini' onClick={this.onGetPay.bind(this, item.id)}>立即支付</Button>}
                              <Button type='warn' size='mini' onClick={this.onCancelOrder.bind(this, item.id)}>关闭订单</Button>
                            </View>
                          )
                        }
                        {
                          item.status.toString() === OrderStatus.Completed.toString() && (
                            <View className='order-panel-footer ratina-bd bd-t'>
                              {/* {item.shouldComment && <Button type='default' size='mini' onClick={this.gotoComment.bind(this, item.id)}>评价</Button>} */}
                              {/* <Button type='default' size='mini' onClick={this.repeatBuy.bind(this, item.id)}>再次购买</Button> */}
                              {item.express && <Button type='primary' size='mini' onClick={this.gotoExpress.bind(this, item.express!.code100, item.expressNumber)}>查看物流</Button>}
                            </View>
                          )
                        }

                        {
                          item.status.toString() == OrderStatus.ShippedAndWaitReceipt.toString() &&
                          (
                            <View className='order-panel-footer ratina-bd bd-t'>
                              {item.express && <Button type='primary' size='mini' onClick={this.gotoExpress.bind(this, item.express!.code100, item.expressNumber)}>查看物流</Button>}
                              <Button type='default' size='mini' onClick={this.confirmResolve.bind(this, item.id)}>确认收货</Button>
                            </View>
                          )
                        }
                      </View>
                    ))
                  }
                </ScrollView>
              </AtTabsPane>
            ))
          }
        </AtTabs>
      </View>
    )
  }
}

export default Index
